package cn.edu.sdjzu.xg.eagle.factory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;



public class DaoFactory {
    private static final String daoPackageName = "cn.edu.sdjzu.xg.eagle.dao";
    private static final Logger LOGGER = LoggerFactory.getLogger(DaoFactory.class);

    // 隐藏构造器，因为这个类只包含静态方法
    private DaoFactory() {
    }

    /**
     * 泛型方法，获取 DAO 接口类型的实现类对象
     *
     * @param daoInterface
     * @param daoClassName
     * @return
     * @param <T>
     * @throws RuntimeException 调用者无须处理异常
     */
    public static <T> T getDao(Class<T> daoInterface, String daoClassName) throws RuntimeException {
        try {
            String fullClassName = daoPackageName + "." + daoClassName;
            Class<?> clazz = Class.forName(fullClassName);
            if (!daoInterface.isAssignableFrom(clazz)) {
                String errorMsg = "类 " + fullClassName + " 没有实现接口 " + daoInterface.getName();
                LOGGER.error(errorMsg);
                throw new RuntimeException(errorMsg);
            }

            // 检查是否有 getInstance 方法
            java.lang.reflect.Method getInstanceMethod = clazz.getMethod("getInstance");
            return (T) getInstanceMethod.invoke(null);
        } catch (ClassNotFoundException e) {
            String errorMsg = "在包 " + daoPackageName + " 中找不到DAO类 " + daoClassName;
            LOGGER.error(errorMsg, e);
            throw new RuntimeException(errorMsg, e);
        } catch (Exception e) {
            String errorMsg = "在实例化DAO类 " + daoClassName + " 时发生错误";
            LOGGER.error(errorMsg, e);
            throw new RuntimeException(errorMsg, e);
        }
    }
}
